package com.neusoft.weixin.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class FreeMarkerUtil {
	
	private static Configuration cfg;
	private static String parentPath = "/web";
	private static String templatePath;
	
	
	/**
	 * 生成静态界面
	 * @param map
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	public static String createHtml(Map<String,String> map,HttpServletRequest request) throws Exception{
		
		initFreeMarker(request);
		
		/* 在整个应用的生命周期中，这个工作你可以执行多次 */
		/* 获取或创建模板*/
		Template temp = cfg.getTemplate("freeMarker.ftl",Locale.CHINA);
		String fileName = "/html/"+new Date().getTime()+".html";
		File html = new File(parentPath,fileName);
		FileOutputStream fos = new FileOutputStream(html);
		Writer out = new OutputStreamWriter(fos,"UTF-8");

		temp.process(map, out);
		out.flush();
		
		return fileName;
	}


	/**
	 * 初始化freeMarker配置
	 * @param request
	 * @throws IOException
	 */
	private static void initFreeMarker(HttpServletRequest request)
			throws IOException {
		parentPath = request.getSession().getServletContext().getRealPath("/web");
		if ( null == templatePath || "".equals(templatePath) ){
			templatePath = parentPath+"/html/template";
		}
		if ( null == cfg ){
			cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(templatePath));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setEncoding(Locale.CHINA, "UTF-8");
		}
	}

}
